<template>
  <div class="user-management-container">
    <!-- 操作区域卡片 -->
    <el-card class="operation-card" shadow="hover">
      <div class="operation-area">
        <el-button type="primary" @click="showAddModal" class="action-button">
          <i class="el-icon-plus"></i> 新增用户
        </el-button>

        <!-- 搜索区域 -->
        <div class="search-area">
          <el-input
              placeholder="登录名"
              v-model="searchLoginName"
              clearable
              prefix-icon="el-icon-user"
              class="search-input"
          ></el-input>

          <el-input
              placeholder="姓名"
              v-model="searchName"
              clearable
              prefix-icon="el-icon-edit"
              class="search-input"
          ></el-input>

          <el-input
              placeholder="手机号"
              v-model="searchPhone"
              clearable
              prefix-icon="el-icon-mobile-phone"
              class="search-input"
          ></el-input>

          <el-select
              v-model="searchRoleId"
              placeholder="角色"
              clearable
              class="search-select"
          >
            <el-option
                v-for="role in roleList"
                :key="role.rid"
                :label="role.name"
                :value="role.rid"
            ></el-option>
          </el-select>

          <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleSearch"
              class="search-button"
          >
            搜索
          </el-button>

          <!-- 新增的重置按钮 -->
          <el-button
              type="info"
              icon="el-icon-refresh"
              @click="handleReset"
              class="search-button"
          >
            重置
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="data-card" shadow="hover">
      <el-table
          :data="tableData"
          style="width: 100%"
          v-loading="loading"
          class="data-table"
          :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
      >
        <el-table-column
            type="index"
            label="序号"
            width="100"
            align="center"
            :index="calculateIndex"
        ></el-table-column>

        <el-table-column
            prop="loginName"
            label="登录名"
            width="160"
            align="center"
        ></el-table-column>

        <el-table-column
            prop="name"
            label="姓名"
            width="160"
            align="center"
        ></el-table-column>

        <el-table-column
            prop="phone"
            label="手机号"
            width="230"
            align="center"
        ></el-table-column>

        <el-table-column
            prop="role.name"
            label="角色"
            width="160"
            align="center"
        ></el-table-column>

        <el-table-column
            label="操作"
            width="400"
            align="center"
            fixed="right"
        >
          <template slot-scope="scope">
            <el-button
                @click="handleEdit(scope.row)"
                type="primary"
                size="mini"
                class="action-button"
            >
              <i class="el-icon-edit"></i> 修改
            </el-button>
            <el-button
                type="danger"
                @click="handleDelete(scope.row)"
                size="mini"
                class="action-button"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增用户模态框 -->
    <el-dialog
        title="新增用户"
        :visible.sync="addDialogVisible"
        width="500px"
        custom-class="tech-dialog"
        :before-close="handleClose"
    >
      <el-form
          :model="addForm"
          :rules="rules"
          ref="addForm"
          label-width="100px"
          class="tech-form"
      >
        <el-form-item label="登录名" prop="loginName">
          <el-input
              v-model="addForm.loginName"
              placeholder="请输入登录名"
              prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input
              v-model="addForm.name"
              placeholder="请输入姓名"
              prefix-icon="el-icon-edit"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              type="password"
              v-model="addForm.password"
              placeholder="请输入密码"
              prefix-icon="el-icon-lock"
              show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
              v-model="addForm.phone"
              placeholder="请输入手机号"
              prefix-icon="el-icon-mobile-phone"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="rid">
          <el-select
              v-model="addForm.rid"
              placeholder="请选择角色"
              class="tech-select"
          >
            <el-option
                v-for="role in roleList"
                :key="role.rid"
                :label="role.name"
                :value="role.rid"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false" class="cancel-button">取消</el-button>
          <el-button type="primary" @click="submitForm" class="confirm-button">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改用户模态框 -->
    <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="500px"
        custom-class="tech-dialog"
        :before-close="handleEditClose"
    >
      <el-form
          :model="editForm"
          :rules="rules"
          ref="editFormRef"
          label-width="100px"
          class="tech-form"
      >
        <el-form-item label="用户ID" prop="uid">
          <el-input
              v-model="editForm.uid"
              disabled
              class="disabled-input"
          ></el-input>
        </el-form-item>
        <el-form-item label="登录名" prop="loginName">
          <el-input
              v-model="editForm.loginName"
              placeholder="请输入登录名"
              prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input
              v-model="editForm.name"
              placeholder="请输入姓名"
              prefix-icon="el-icon-edit"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              type="password"
              v-model="editForm.password"
              placeholder="不修改则留空"
              prefix-icon="el-icon-lock"
              show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
              v-model="editForm.phone"
              placeholder="请输入手机号"
              prefix-icon="el-icon-mobile-phone"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="rid">
          <el-select
              v-model="editForm.rid"
              placeholder="请选择角色"
              class="tech-select"
          >
            <el-option
                v-for="role in roleList"
                :key="role.rid"
                :label="role.name"
                :value="role.rid"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false" class="cancel-button">取消</el-button>
          <el-button type="primary" @click="submitEditForm" class="confirm-button">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request';

export default {
  data() {
    return {
      tableData: [],
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        loginName: '',
        name: '',
        password: '',
        phone: '',
        rid: null
      },
      editForm: {
        uid: '',
        loginName: '',
        name: '',
        password: '',
        phone: '',
        rid: null
      },
      roleList: [],
      rules: {
        loginName: [
          { required: true, message: '请输入登录名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度至少6位', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        rid: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      searchLoginName: '',
      searchName: '',
      searchPhone: '',
      searchRoleId: null,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false
    }
  },
  mounted(){
    this.fetchUserList();
    this.fetchRoleList();
  },
  methods: {
    calculateIndex(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    handleSearch() {
      this.currentPage = 1;
      this.fetchUserList();
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchUserList();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchUserList();
    },
    fetchUserList() {
      this.loading = true;
      request.get('/user/list', {
        params: {
          page: this.currentPage,
          size: this.pageSize,
          loginName: this.searchLoginName,
          name: this.searchName,
          phone: this.searchPhone,
          roleId: this.searchRoleId
        }
      })
          .then(response => {
            this.tableData = response.data.data.records;
            this.total = response.data.data.total;
            this.loading = false;
          })
          .catch(error => {
            console.error('获取用户列表失败:', error);
            this.$message.error('获取用户列表失败');
            this.loading = false;
          });
    },
    fetchRoleList() {
      request.get('/role/list')
          .then(response => {
            this.roleList = response.data.data.roleList;
          })
          .catch(error => {
            console.error('获取角色列表失败:', error);
            this.$message.error('获取角色列表失败');
          });
    },
    showAddModal() {
      this.addForm = {
        loginName: '',
        name: '',
        password: '',
        phone: '',
        rid: null
      };
      this.addDialogVisible = true;
    },
    handleEdit(row) {
      this.editForm = {
        uid: row.uid,
        loginName: row.loginName,
        name: row.name,
        password: '',
        phone: row.phone,
        rid: row.role ? row.role.rid : null
      };
      this.editDialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm('确定要删除该用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'tech-message-box'
      }).then(() => {
        request.delete(`/user/delUser/${row.uid}`)
            .then(() => {
              this.$message.success('删除成功');
              this.fetchUserList();
            })
            .catch(error => {
              console.error('删除失败:', error);
              this.$message.error('删除失败');
            });
      }).catch(() => {});
    },
    handleClose(done) {
      this.$confirm('确定要关闭吗？未保存的内容将会丢失', '提示', {
        type: 'warning',
        customClass: 'tech-message-box'
      }).then(() => {
        done();
      }).catch(() => {});
    },
    handleEditClose(done) {
      this.$confirm('确定要关闭吗？未保存的内容将会丢失', '提示', {
        type: 'warning',
        customClass: 'tech-message-box'
      }).then(() => {
        done();
      }).catch(() => {});
    },
    submitForm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          request.post(`/user/addUser/`, this.addForm)
              .then(() => {
                this.$message.success('新增用户成功');
                this.addDialogVisible = false;
                this.fetchUserList();
              })
              .catch(error => {
                console.error('新增用户失败:', error);
                this.$message.error('新增用户失败');
              });
        }
      });
    },
    submitEditForm() {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          const updateData = {
            uid: this.editForm.uid,
            loginName: this.editForm.loginName,
            name: this.editForm.name,
            phone: this.editForm.phone,
            rid: this.editForm.rid
          };
          if (this.editForm.password) {
            updateData.password = this.editForm.password;
          }
          request.put(`/user/updateUser`, updateData)
              .then(() => {
                this.$message.success('修改用户成功');
                this.editDialogVisible = false;
                this.fetchUserList();
              })
              .catch(error => {
                console.error('修改用户失败:', error);
                this.$message.error('修改用户失败');
              });
        }
      });
    },
    handleReset() {
      // 清空搜索条件
      this.searchLoginName = '';
      this.searchName = '';
      this.searchPhone = '';
      this.searchRoleId = null; // 清空角色筛选

      // 重置分页到第一页
      this.currentPage = 1;

      // 触发重新搜索（清空条件后查询全部数据）
      this.fetchUserList();
    },

  }
}
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 80px);
}

.operation-card {
  margin-bottom: 20px;
  border-radius: 8px;
  border: none;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.data-card {
  border-radius: 8px;
  border: none;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.operation-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.search-area {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-input {
  width: 180px;
}

.search-select {
  width: 180px;
}

.search-button {
  margin-left: 10px;
  transition: all 0.3s;
  border-radius: 4px;
}

/* 重置按钮的样式（与搜索按钮区分） */
.el-button.info {
  background-color: #f4f4f5;
  color: #606266;
  border-color: #dcdfe6;
}

.el-button.info:hover {
  background-color: #e9e9eb;
  color: #4a4c51;
}

.search-button {
  margin-left: 10px;
}
.search-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(58, 123, 213, 0.2);
}

.action-button {
  transition: all 0.3s;
  border-radius: 4px;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(58, 123, 213, 0.2);
}

.data-table {
  margin-top: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/deep/ .tech-dialog {
  border-radius: 8px;
  background: linear-gradient(145deg, #f5f7fa, #e4e7ed);
  border: 1px solid rgba(58, 123, 213, 0.2);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

/deep/ .tech-dialog .el-dialog__header {
  background: linear-gradient(90deg, #3a7bd5, #00d2ff);
  border-radius: 8px 8px 0 0;
  padding: 15px 20px;
}

/deep/ .tech-dialog .el-dialog__title {
  color: white;
  font-weight: 600;
}

/deep/ .tech-dialog .el-dialog__headerbtn .el-dialog__close {
  color: white;
}

.tech-form {
  padding: 20px;
}

/deep/ .tech-form .el-input__inner {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
}

/deep/ .tech-form .el-input__inner:hover {
  border-color: #c0c4cc;
}

/deep/ .tech-form .el-input__inner:focus {
  border-color: #3a7bd5;
  box-shadow: 0 0 0 2px rgba(58, 123, 213, 0.2);
}

.tech-select {
  width: 100%;
}

.disabled-input /deep/ .el-input__inner {
  background-color: #f5f7fa;
  color: #909399;
  cursor: not-allowed;
}

.cancel-button {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
  color: #606266;
  transition: all 0.3s;
}

.cancel-button:hover {
  background-color: #e4e7ed;
  border-color: #c0c4cc;
  color: #606266;
}

.confirm-button {
  background: linear-gradient(90deg, #3a7bd5, #00d2ff);
  border: none;
  transition: all 0.3s;
}

.confirm-button:hover {
  background: linear-gradient(90deg, #2c5fb3, #00b7e6);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(58, 123, 213, 0.3);
}

/deep/ .tech-message-box {
  border-radius: 8px;
  background: linear-gradient(145deg, #f5f7fa, #e4e7ed);
  border: 1px solid rgba(58, 123, 213, 0.2);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

/deep/ .tech-message-box .el-message-box__header {
  background: linear-gradient(90deg, #3a7bd5, #00d2ff);
  border-radius: 8px 8px 0 0;
  padding: 15px 20px;
}

/deep/ .tech-message-box .el-message-box__title {
  color: white;
  font-weight: 600;
}

/deep/ .tech-message-box .el-message-box__content {
  padding: 20px;
}

/deep/ .tech-message-box .el-message-box__btns {
  padding: 10px 20px 20px;
}
</style>